let express = require('express');
let crypto = require('crypto');
let router = express.Router();

router.post('/', function (req, res, next) {
    let params = req.body;

    if (params.name === undefined || params.name === "") {
        res.json({"success": false, "message": "登录用户名不能为空！"});
        return;
    }

    if (params.password === undefined || params.password === "") {
        res.json({"success": false, "message": "密码不能为空！"});
        return;
    }

    req.app.db.query("select * from user where name = ? and password = ?", [params.name, crypto.createHash("md5").update(params.password).digest('hex')], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "用户名密码错误！"});
            return;
        }

        let user = results[0];
        if (user.isActived !== 1) {
            req.session.destroy();
            res.clearCookie("user");
            res.clearCookie(global.cookieIndentity);delete req.session;
            res.json({"success": false, "message": "当前用户已禁用！"});

            return;

        }

        // 用户在线或没有正常退出，并且不在一个客户端登录
        if (global.users[user.id] !== req.sessionID) {
            // 有socket连接，但连接的不是本机
            if (global.clients[user.id] !== undefined && global.clients[user.id].sessionId !== req.sessionID) {
                if (global.clients[user.id].disconnectedTime === undefined) {
                    res.json({"success": false, "message": "当前帐号已在其他机器登录！"});
                    return;
                }
                else {
                    let distanceSecond = (new Date() - global.clients[user.id].disconnectedTime) / 1000;
                    console.log("时差：" + distanceSecond);
                    if (distanceSecond < global.socket.disconnectedTime) {
                        res.json({"success": false, "message": "当前帐号已在其他机器登录！"});
                        return;
                    }
                }
            }
        }


        req.app.db.query("select * from role where id = ?", [user.roleId], function (err, results) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            if (results.length === 0) {
                res.json({"success": false, "message": "用户角色信息错误！"});
                return;
            }

            let role = results[0];
            delete user.password;
            req.session.user = user;
            req.session.role = role;
            global.users[user.id] = req.sessionID;
            global.clients[user.id] = undefined;
            res.cookie("user", JSON.stringify({"id": user.id, "name": user.trueName}));
            res.cookie("userId", user.id);
            res.cookie("sessionId", req.sessionID);
            res.json({"success": true, "data": user, "message": "登录成功！"});
        });
    });
});

module.exports = router;